<?php
/**
 * CreateTime: 2023/11/16 18:49
 * User:LinQ
 */

namespace App\Models\Users;

use App\Models\Auth\RoleModel;
use App\Models\BasicModel;
use App\Models\CompanyDepartment\CompanyModel;
use App\Models\CompanyDepartment\DepartmentModel;

class UsersModel extends BasicModel
{
    protected $table = 'users';

    protected $primaryKey = 'user_id';

    protected $fillable = [
        'user_id',
        'com_id',
        'name',
        'password',
        'email',
        'phone',
        'union_id',
        'enable_status',
        'status',
        'pu_key',
        'pv_key',
        'staff_last_login_time',
        'created_at',
        'updated_at',
    ];

    protected $casts = [
        'user_id' => 'integer',
        'com_id' => 'integer',
        'name' => 'string',
        'password' => 'string',
        'email' => 'string',
        'phone' => 'string',
        'union_id' => 'string',
        'enable_status' => 'integer',
        'status' => 'integer',
        'pu_key' => 'string',
        'pv_key' => 'string',
        'staff_last_login_time' => 'string', // 这里给string 返回 2023-11-23 17:13:20 否则  "2023-11-23T09:04:40.000000Z";
        'created_at' => 'string',
        'updated_at' => 'string',
    ];

    protected $hidden = [
        'pu_key',
        'pv_key',
        'password',
        'enable_status',
        'status',
        'created_at',
        'updated_at',
    ];

    /**
     * 获取用户下角色
     * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
     */
    public function roles(): \Illuminate\Database\Eloquent\Relations\BelongsToMany
    {
        return $this->belongsToMany(RoleModel::class,'user_role','user_id','role_id');
    }

    /**
     * 获取用户的角色
     * @return mixed
     */
    public function auths($select = ["*"]): mixed
    {
        return $this->roles()->with(['auths'=>function($query) use ($select){
            $query->select($select);
        }])->get()->pluck('auths')->flatten()->unique('auth_id')->toArray();
    }

    /**
     * 获取用户的公司信息
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     */
    public function company(): \Illuminate\Database\Eloquent\Relations\BelongsTo
    {
        return $this->belongsTo(CompanyModel::class,'com_id','company_id');
    }

    /**
     * 获取用户的部门id
     * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
     */
    public function departments(): \Illuminate\Database\Eloquent\Relations\BelongsToMany
    {
        return $this->belongsToMany(DepartmentModel::class,'department_user','user_id','department_id');
    }

    /**
     * 根据用户账号获取用户信息
     * @param string $account
     * @return mixed
     */
    public function getUsersInfoByAccount(string $account): mixed
    {
        return $this
            ->where('account',$account)
            ->where('status',1)
            ->where('enable_status',1)
            ->first();
    }
}
